<template>
	<view class="page-box">
		<view class="select-currency" @click="show = true">
			<view>{{$t('my.selectCurrency')}}</view>
			<view class="select-btn">
				<image :src="`../../static/img/my/${currencyCode}.png`" style="width: 40rpx; height: 40rpx;margin-right: 6rpx;"></image>
				{{currencyCode}}
				<image src="../../static/img/my/select-icon.png" style="width: 15rpx; height: 25rpx;margin-left: 6rpx;"></image>
			</view>
		</view>
		<!-- <view class="recharge-network">
			<view class="title-box">充值网络</view>
			<view class="select-network">
				选择网络
				<image src="../../static/img/my/ss.png" style="width: 20rpx; height: 11rpx;"></image>
			</view>
		</view> -->
		
		<view class="money-box">
			<up-input :placeholder="$t('trade.placeholder3')" border="none" v-model="money" type="decimal"></up-input>
		</view>
		<view class="tip-box">{{$t('my.minCurrency')}}：{{limit.minInAmount}}</view>
		
		<view class="btn-box">
			<u-button :text="$t('confirm')" type="success" shape="circle" color="#1C5FFF" @click="inBalanceFn"></u-button>
		</view>
		
		<up-picker :show="show" :columns="columns" keyName="currencyCode" closeOnClickOverlay @close="show = false" @cancel="show = false" @confirm="confirm"></up-picker>
		
		<view class="bottom-box"></view>
	</view>
</template>

<script setup>
	import {ref} from 'vue';
	import {getUserInfo,inBalance,getcurrencyCode} from '@/common/api/common.js'
	import { onLoad,onShow, } from '@dcloudio/uni-app'
	import { ethers } from "ethers";
	import { useI18n } from 'vue-i18n';
	import USDC from'@/common/USDC.json'
	import WNA from'@/common/USDC.json'
	const {t} = useI18n();
	const money = ref('')
	const address = ref('')
	const stakingAddress = ref('')
	const limit = ref({})
	const currencyCode = ref('USDC')
	const show = ref(false);
	const columns = ref([[]]);
	
	const inBalanceFn = async () => {
		if(!money.value){
			uni.$u.toast(t('my.placeholder'))
			return;
		}
		if(Number(money.value) < Number(limit.value.minInAmount)) {
			uni.$u.toast(t('minCurrency') + limit.value.minInAmount)
			return;
		}
		const accounts = await window.ethereum.request({method: 'eth_requestAccounts'})
		// const waiAddress = stakingAddress.value;
		const waiAddress = limit.value.inAddress;
		const targetAddress = ethers.utils.getAddress(waiAddress);
		const provider = new ethers.providers.Web3Provider(window.ethereum);
		const signer = provider.getSigner(accounts[0]);
		const contract = limit.value.contractAddress;
		let abi;
		let num;
		if(currencyCode.value == 'USDC') {
			// contract = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
			abi = USDC;
			num = 6
		}else if(currencyCode.value == 'WNA') {
			// contract = '0x6a11e70fD64F066687DFD0884c91Cbe262E216C4';
			abi = WNA;
			num = 18;
		}
		const abiContract = new ethers.Contract(contract,abi,signer);
		const allow = await abiContract.allowance(accounts[0],contract);
		const allowBalance = ethers.utils.formatEther(allow.toString());
		const maxUint256 = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff';
		try {
			if(Number(allowBalance) < Number(money.value)) {
				const approveTx = await abiContract.approve(contract, maxUint256);
			}
			let amount = ethers.utils.parseEther(money.value)
			const Tx = await abiContract.transfer(targetAddress,ethers.utils.parseUnits(money.value, num),{ gasLimit: 500000 })
			if (Tx.hash) {
				uni.$u.toast(t('success'))
				const res = await inBalance({txHash: Tx.hash})
			} else {
				uni.$u.toast(t('sb'))
			}
		} catch (error) {
			// console.log(error);
			uni.$u.toast(t('sb'))
		}
	}
	
	const getUserInfoFn = async () => {
		const res = await getUserInfo({
			address: address.value
		})
		if (res.status == 0) {
			stakingAddress.value = res.result.stakingAddress
		} else {
			// uni.$u.toast(res.errorMessage)
		}
	}
	
	const getcurrencyCodeFn = async () => {
		const res = await getcurrencyCode({currencyCode: '', page: 0, pageSize: 10})
		if (res.status == 0) {
			res.result.content.map((item,index) => {
				item.id = index + 1
			})
			columns.value[0] = res.result.content
			limit.value = res.result.content[0]
		} else {
			// uni.$u.toast(res.errorMessage)
		}
	}
	
	const confirm = (e) => {
	  show.value = false;
	  if(e.value[0].currencyCode == 'XTTA') {
		  uni.$u.toast(t('notYetOpen'))
		  return
	  }
	  currencyCode.value = e.value[0].currencyCode
	  limit.value = e.value[0]
	};
	
	const goPage = url =>{
		uni.navigateTo({
			url:url
		})
	}
	
	onLoad((options) => {
		address.value = uni.getStorageSync('address');
		getcurrencyCodeFn();
	})
	
	onShow(() => {
		if (address.value) {
			getUserInfoFn();
			getcurrencyCodeFn();
		}
	})
</script>

<style lang="scss" scoped>
	.page-box{
		padding: 40rpx;
		box-sizing: border-box;
		
		.select-currency{
			display: flex;
			justify-content: space-between;
			align-items: center;
			background-color: #f5f5f5;
			border-radius: 16rpx;
			height: 80rpx;
			padding: 0 40rpx;
			box-sizing: border-box;
			color: #1f1f1f80;
			
			.select-btn{
				display: flex;
				justify-content: space-between;
				align-items: center;
				color: #1f1f1f;
			}
		}
		
		.recharge-network{
			background-color: #f5f5f5;
			border-radius: 16rpx;
			padding: 40rpx;
			box-sizing: border-box;
			margin-top: 20rpx;
			color: #1f1f1f80;
			
			.select-network{
				background-color: #ffffff;
				margin-top: 20rpx;
				height: 80rpx;
				line-height: 80rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 0 20rpx;
				box-sizing: border-box;
				border-radius: 16rpx;
			}
		}
		.money-box{
			background-color: #f5f5f5;
			border-radius: 16rpx;
			height: 80rpx;
			padding: 0 40rpx;
			box-sizing: border-box;
			color: #1f1f1f80;
			display: flex;
			align-items: center;
			margin-top: 20rpx;
		}
		.tip-box{
			text-align: right;
			font-size: 24rpx;
			color: #1f1f1f80;
			padding-top: 20rpx;
		}
		
		.btn-box{
			margin: 50rpx auto 0;
			::v-deep .u-button{
				height:88rpx !important;
			}
		}
	}
</style>